package com.example.shop.modules.sys.service.impl;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.shop.dto.CartParam;
import com.example.shop.persistence.entity.Cart;
import com.example.shop.persistence.mapper.CartMapper;
import com.example.shop.modules.sys.service.ICartService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.shop.utils.MPPageFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 购物车 服务实现类
 * </p>
 *
 * @author jason
 * @since 2019-12-17
 */
@Service
public class CartServiceImpl extends ServiceImpl<CartMapper, Cart> implements ICartService {

    @Autowired
    private CartMapper cartMapper;

    /* 加入购物车 */
    @Override
    public void saveCart(CartParam cartParam){
        //0.插入关联的属性模板值
        List<Cart> list = resolveAttributeBeanJSON(cartParam.getAttrValues());
        for(Cart cart: list){
            Integer userID = cartParam.getUserID();
            cart.setUserID(userID);
            if(cart.getId() == null){
                // 新增
                QueryWrapper ew = new QueryWrapper();
                // 先查询该商品是否已经在购物车中 按商品ID和商品规格ID查询
                ew.eq("userID", userID);
                ew.eq("goodsID", cart.getGoodsID());
                if(cart.getStandardID() != null){
                    // 如果有规格参数 带规格参数查询
                    ew.eq("standardID", cart.getStandardID());
                }
                Cart one = cartMapper.selectOne(ew);
                if(cart.getGoodsNum() == 0){
                    // 如果商品数量为0 直接删除该商品
                    this.deleteCarts(String.valueOf(one.getId()));
                }
                if(one != null){
                    // 如果购物车中已存在该商品 商品数量+1
                    cart.setId(one.getId());
                    cart.setGoodsNum(one.getGoodsNum() + 1);
                    cartMapper.updateById(cart);
                }else{
                    // 直接插入数据
                    cartMapper.insert(cart);
                }
            }else{
                // 更新
                cartMapper.updateById(cart);
            }
        }

    }

    /* 数据转换 */
    public static List<Cart> resolveAttributeBeanJSON(String attributeBeanJSON) {
        List<Cart> attributeBeanList = new ArrayList<>();
        try {
            if (StrUtil.isNotEmpty(attributeBeanJSON)) {
                String decode = URLDecoder.decode(attributeBeanJSON, CharsetUtil.UTF_8);
                attributeBeanList = JSON.parseArray(decode, Cart.class);
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return attributeBeanList;
    }

    @Override
    public int deleteCarts(String ids){
        // 先转换为字符串数组
        String[] strs = ids.split(",");
        List<Long> ints = new LinkedList<Long>();
        for(String id: strs){
            // 在转换为long 类型数组
            ints.add(Long.valueOf(id));
        }
        //批量删除
        return cartMapper.deleteBatchIds(ints);
    }

    //分页查询
    @Override
    public IPage<Cart> selectListCart(Integer page, Integer pageSize, Integer userID, Integer isCollect){
        Page<Cart> pages = MPPageFactory.createPage(page,pageSize);
        QueryWrapper ew = new QueryWrapper();
        if (userID != null){
            ew.eq("userID",userID);
        }
        if(isCollect != null){
            ew.eq("isCollect", isCollect);
        }
        ew.orderByDesc("createTime");
        return pages.setRecords(cartMapper.selectListCart(pages,ew));
    }


    // 查询购物车商品数
    @Override
    public int selectContCart(Integer userID){
        QueryWrapper ew = new QueryWrapper();
        ew.eq("userID",userID);
        ew.eq("isCollect", 0);
        return cartMapper.selectCount(ew);
    }

    // 查询是否包含某件商品
    @Override
    public int selectInclude(Integer userID, Integer goodsID, Integer isCollect){
        QueryWrapper ew = new QueryWrapper();
        ew.eq("userID",userID);
        ew.eq("goodsID", goodsID);
        if(isCollect != null){
            ew.eq("isCollect", isCollect);
        }
        return cartMapper.selectCount(ew);
    }

    // 根据商品ID删除
    @Override
    public int deleteCart(Integer userID, Integer goodsID, Integer isCollect){
        QueryWrapper ew = new QueryWrapper();
        ew.eq("userID",userID);
        ew.eq("goodsID",goodsID);
        if(isCollect != null){
            ew.eq("isCollect", isCollect);
        }
        return cartMapper.delete(ew);
    }

}
